package com.app.asktom.component;

import java.text.DecimalFormat;
import java.util.ArrayList;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.provider.ContactsContract;
import android.telephony.SmsManager;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;

public class DeviceHelper {
	
	private static String _latitude="";
	private static String _longitude="";
	private static boolean isSetGPS = false;
	private static String _updateLatitude = "";
	private static String _updateLongitude = "";
	
	public static void storeUpdateLocation(double longitude, double latitude) {
		DecimalFormat df = new DecimalFormat("##.########");
		DeviceHelper._updateLatitude = df.format(latitude);
		DeviceHelper._updateLongitude = df.format(longitude);
	}
	
	public static String getUpdateLatitude() {
		return DeviceHelper._updateLatitude;
	}
	
	public static String getUpdateLongitude() {
		return DeviceHelper._updateLongitude;
	}
	
 	public static boolean hasConnection(Activity activity) {
	    ConnectivityManager cm = (ConnectivityManager) activity.getSystemService(
	            Context.CONNECTIVITY_SERVICE);

        NetworkInfo wifiNetwork = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        if (wifiNetwork != null && wifiNetwork.isConnected()) {
          return true;
        }

        NetworkInfo mobileNetwork = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        if (mobileNetwork != null && mobileNetwork.isConnected()) {
          return true;
        }

        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        if (activeNetwork != null && activeNetwork.isConnected()) {
          return true;
        }
		return false;
	}
	
	public static void storeCoordinates(double longitude, double latitude) {
		DecimalFormat df = new DecimalFormat("##.########");
		DeviceHelper._latitude = df.format(latitude);
		DeviceHelper._longitude = df.format(longitude);
	}
	
	public static void resetCoordinate() {
		DeviceHelper._latitude = "";
		DeviceHelper._longitude = "";
	}
	
	public static String getLongtitude() {
		return DeviceHelper._longitude;
	}
	
	public static String getLatitude() {
		return DeviceHelper._latitude;
	}
	
	/**
	 * Get gmail of user
	 * @param activity
	 * @return gmail of user else "no email"
	 */
	public static String getUserEmail(Activity activity) {
		AccountManager manager = AccountManager.get(activity);
		Account[] accounts = manager.getAccountsByType("com.google");
		String userEmail = "no email";
		if(accounts[0].name != null) {
			userEmail = accounts[0].name;
		}
		return userEmail;
	}
	
	/**
	 * Get user phone number.
	 * @param activity
	 * @return user number else "no number"
	 */
	public static String getUserPhoneNumber(Activity activity) {
	     String number = "no number";
	     String service = Context.TELEPHONY_SERVICE;
	     TelephonyManager tel_manager = (TelephonyManager) 
	    		 activity.getSystemService(service);
	     int device_type = tel_manager.getPhoneType();

	     switch (device_type) {
	           case (TelephonyManager.PHONE_TYPE_CDMA):
	              number = tel_manager.getLine1Number();
	           break;
	     }
	     return number;		
	}
	
	public static ArrayList<String> getAllPhoneNumber(
			Activity activity) {
		ArrayList<String> phoneNumbers = new ArrayList<String>();
		Cursor phones = activity.getContentResolver()
				.query(ContactsContract.CommonDataKinds
				.Phone.CONTENT_URI, null,null,null, null);
        while (phones.moveToNext()) {
//	        String Name=phones.getString(
//        		phones.getColumnIndex(ContactsContract.
//        		CommonDataKinds.Phone.DISPLAY_NAME));
//	        String Number=phones.getString(
//        		phones.getColumnIndex(ContactsContract
//        		.CommonDataKinds.Phone.NUMBER));
	        phoneNumbers.add(phones.getString(
	        		phones.getColumnIndex(ContactsContract
    				.CommonDataKinds.Phone.NUMBER)));
        }
        return phoneNumbers;
	}

	/**
	 * Send sms
	 * @param activity
	 * @param phoneNo
	 * @param msg
	 * @return true if successfully send else false
	 */
	public static boolean sendSms(Activity activity, String phoneNo,
    		String msg) {
    	
    	TelephonyManager telMgr = (TelephonyManager) 
    			activity.getSystemService(Context.TELEPHONY_SERVICE);
    	int simState = telMgr.getSimState();
    	
    	if(simState == TelephonyManager.SIM_STATE_READY) {
        	try {
            	SmsManager smsManager = SmsManager.getDefault();
            	smsManager.sendTextMessage(phoneNo, null, msg, null,
            			null);
            	Log.d("DEBUG", msg+"=============");
            	Toast.makeText(activity.getApplicationContext(), 
    					"SMS Sent!",Toast.LENGTH_LONG).show();
    			return true;
        	} catch (Exception e) {
    			Toast.makeText(activity.getApplicationContext(),
    					"SMS failed, please make sure you have load " +
    					"and try again",Toast.LENGTH_LONG).show();
        	}    		
    	} else if(simState == TelephonyManager.SIM_STATE_ABSENT) {
    		Toast.makeText(activity, "Sim card not available",
    				Toast.LENGTH_LONG).show();
    	} else {
    		Toast.makeText(activity, "Failed to send sms",
    				Toast.LENGTH_LONG).show();
    	}
    	return false;
    }	
    
	public static void setGPS(boolean isSetGPS) {
		DeviceHelper.isSetGPS = isSetGPS;
	}
	
	public static boolean isSetGPS() {
		return DeviceHelper.isSetGPS;
	}
	
//    private static void displayAlert(Activity activity, String message) {
//	        // TODO Auto-generated method stub
//	
//	        new AlertDialog.Builder(activity)
//	                .setMessage(message)
//	                .setCancelable(false)
//	                // .setIcon(R.drawable.alert)
//	                .setPositiveButton("ok",
//	                        new DialogInterface.OnClickListener() {
//	                            public void onClick(DialogInterface dialog,
//	                                    int id) {
//	                                Log.d("I am inside ok", "ok");
//	                                dialog.cancel();
//	                            }
//	                        })
//	
//	                .show();
//	
//	}

}
